<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="编辑多属性"
    width="1200"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      class="mt-3"
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="100"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="" prop="name">
            <el-checkbox-group
              v-model="checkboxGroup"
              @change="handleCheckAllChange"
              :min="1"
            >
              <el-checkbox
                :label="item"
                border
                v-for="(item, index) in checkboxList"
                :key="index"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="4">
          <el-form-item label="" label-width="0" prop="status">
            <el-select
              v-model="languages"
              collapse-tags
              placeholder="请选择"
              clearable
              multiple
              class="w-full select-lang"
              @change="changeLang"
            >
              <el-option
                v-for="item in languageOptions &&
                languageOptions.filter((item) => !(item.id === 1 || item.id === 2))"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <List
        class="line"
        ref="listRef"
        :languages="languageSelect"
        v-model="formData.goods_spu_specification"
      ></List>
    </el-form>
    <template #footer>
      <div class="fl" v-if="formData.id">
        <el-checkbox v-model="addOmit" label="添加遗漏规格值名" size="large" />
        <el-checkbox
          v-if="showRecreate"
          v-model="recreate"
          label="重新生成SKU(未审核通过产品才可以重新生成SKU)"
          size="large"
        />
      </div>
      <!-- <div class="flex justify-center py-2"> -->
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
      <!-- </div> -->
    </template>
  </el-dialog>
</template>
<script setup lang="jsx" name="ComModal">
import { reactive, toRefs, getCurrentInstance, nextTick, computed } from "vue";
import List from "./list.vue";
import { ElMessage, ElMessageBox } from "element-plus";
let formData = reactive(inject("form"));
const { proxy } = getCurrentInstance();
const emit = defineEmits(["changeSKU"]);
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
const { languageOptions } = storeToRefs(commonStore);

const data = reactive({
  form: {
    target_lang: [],
  },
  visible: false,
  loading: false,
  formRef: null,
  AttributeName: "",
  checkboxGroup: [],
  load: false,
});

const checkboxList = computed(() => {
  const checkboxList = [];
  formData.value.goods_spu_specification.forEach((item) => {
    checkboxList.push(item.group_name);
  });
  return checkboxList;
});

const showRecreate = computed(() => {
  const minNameObject =
    formData.value.goods_sku.length &&
    formData.value.goods_sku.reduce((minObj, currentObj) => {
      if (currentObj.dev_status > minObj.dev_status) {
        return currentObj;
      }
      return minObj;
    }, formData.value.goods_sku[0]);
  return minNameObject.dev_status > 1;
});

const addOmit = ref(false);
const recreate = ref(false);
const { rules, form, visible, loading, formRef, checkboxGroup, load } = toRefs(data);
const listRef = ref(null);
const languages = ref([]);
const languageSelect = ref([]);
const open = async () => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  languages.value = [10];
  languageSelect.value = [10];

  filterSpecification();
  visible.value = true;
};
// 选择语言把设置show属性
const changeLang = () => {
  languageSelect.value = selectLanguage(languages.value);
  formData.value.goods_spu_specification.forEach((element, e) => {
    element.values.forEach((ele) => {
      if (ele.language_id > 2) {
        if (languageSelect.value.includes(ele.language_id)) {
          ele.show = true;
        } else {
          ele.show = false;
        }
      }
    });
  });
};
// 语言id
const selectLanguage = (list) => {
  let arr = [];
  list.forEach((item) => {
    languageOptions.value.forEach((o) => {
      if (item === o.id) {
        arr.push(o.id);
      }
    });
  });
  return arr;
};

const save = () => {
  let massageArray = [];
  let attributes = [];
  formData.value.goods_spu_specification.forEach((item, i) => {
    if (item.show != false) {
      item.values.forEach((val, v) => {
        if (val.language_id == 2) {
          const encounteredValues = [];
          val.language_values.forEach((lang, l) => {
            attributes.push({
              name: "",
              value: lang.value,
            });
            if (!lang.value) {
              massageArray.push(`请输入 ${item.name} 第 ${l + 1} 个英语属性名称`);
            } else if (encounteredValues.includes(lang.value)) {
              massageArray.push(`在 ${item.name} 中发现重复的英文属性值: ${lang.value}`);
            } else {
              encounteredValues.push(lang.value.trim());
              attributes.push({
                name: "",
                value: lang.value,
              });
            }
          });
        }
      });
    }
  });

  if (massageArray && massageArray.length) {
    return ElMessageBox({
      title: "提示",
      message: <div>{massageArray.map((d) => h("p", null, d))}</div>,
    });
  }

  let newList = JSON.parse(JSON.stringify(formData.value.goods_spu_specification));

  let list = newList
    .filter((k) => {
      if (k.show != false) {
        return k;
      }
    })
    .map((i) => {
      i.values.forEach((j) => {
        if (j.language_id == 2) {
          i.en_value = j.language_values.map((k) => k.value);
          i.first_value = j.language_values.map((k) => k.first_value);
          i.en_name = j.name;
        }
        if (j.language_id == 1) {
          i.cn_value = j.language_values.map((k) => k.value);
          i.cn_name = j.name;
        }
      });
      i.first_value = i.first_value?.length ? i.first_value : i.en_value;
      i.name = i.group_name;
      delete i.values;
      return i;
    });
  let data = {
    spu: formData.value.spu,
    productCategory: formData.value.spu_category,
    attributes: list,
    recreate: recreate.value,
  };

  emit("changeSKU", data, recreate.value, addOmit.value);
};

const handleCheckAllChange = (val) => {
  formData.value.goods_spu_specification.forEach((item) => {
    item.show = checkboxGroup.value.includes(item.group_name);
  });
};

const filterSpecification = () => {
  const checkbox = [];
  formData.value.goods_spu_specification.forEach((item) => {
    if (item.show != false) {
      checkbox.push(item.group_name);
    }
  });
  nextTick(() => {
    checkboxGroup.value = checkbox;
  });
};

const close = () => {
  proxy.resetForm("formRef");
  visible.value = false;
};

defineExpose({ open, close });
</script>
<style lang="scss" scoped>
.el-dialog__footer {
  height: 90px !important;
}

:deep(.select-lang .el-select__tags) {
  background-color: #fafafa;
}

:deep(.select-lang .el-input__wrapper) {
  background-color: #fafafa;
}

.line {
  border-top: 1px dashed rgba(52, 135, 255, 0.2);
  padding-top: 12px;
}
</style>
